package com.huafv.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.huafv.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@WebFilter(filterName = "loginCheckFilter")
public class LoginCheckFilter implements Filter {
    // 路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        String requestURI = httpServletRequest.getRequestURI();
        log.info("拦截到请求URI:{}", requestURI);

        // 无需拦截 URI
        List<String> uris = new ArrayList<>();
        uris.add("/backend/**");
        uris.add("/common/**");
        uris.add("/front/**");
        uris.add("/employee/login");
        uris.add("/employee/logout");
        uris.add("/user/login");
        uris.add("/user/sendMsg");


        // 无需拦截便直接放行
        if(check(requestURI, uris)){
            log.info("请求URI:{}不需要处理", requestURI);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 判断如果已经登录则方行
        Object employee = httpServletRequest.getSession().getAttribute("employee");
        if(!ObjectUtils.isEmpty(employee)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 判断如果已经登录则方行
        Object user = httpServletRequest.getSession().getAttribute("user");
        if(!ObjectUtils.isEmpty(user)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 返回未登录
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param URI 本次请求的URI
     * @param URIS 不需要处理的URI
     * @return bool
     */
    public boolean check(String URI,List<String> URIS){
        for (String val : URIS) {
            boolean match = PATH_MATCHER.match(val, URI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
